package com.calvin.study.multithread.volatiledemo;

import java.util.concurrent.atomic.AtomicInteger;

class Data {
	int number = 0;

	public void addIncrement() {
		number++;
	}

	AtomicInteger atomicNumber = new AtomicInteger(0);

	public void addAtomic() {
		// 先获取值再每次+1
		atomicNumber.getAndIncrement();
	}
}

public class VolatileDemo {

	public static void main(String[] args) {
		Data d = new Data();

		for (int i = 1, len = 20; i <= len; i++) {
			new Thread(new Runnable() {
				public void run() {
					for (int j = 1, jlen = 1000; j <= jlen; j++) {
						d.addAtomic();
					}
				}
			}, "t" + i).start();
		}
		// 需要等待上面20个线程全都计算完成后，查看最终结算结果
		// 为什么是大于2 系统默认两个线程 main 和 gc
		while (Thread.activeCount() > 2) {
			Thread.yield();
		}
		System.out.println(Thread.currentThread().getName() + "\t finally number value:" + d.atomicNumber);
	}
}
